# This will be a program that has a grid, numbers can be input to the cells,
# upon selecting the cells various calculations are automatically done and
# can be displayed in the status bar others can be displayed in a hovering
# tooltip maybe make all stats formatted and copied to the clipboard.

# ##############################################################################
# basicStat
# Developer: Ryan Smith
# Copyright 2008 Ryan Smith
	
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.

# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.

# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
# ##############################################################################



import wx
import os
import wx.grid as gridlib

ID_NEW  = 100
ID_OPEN = 101
ID_SAVE = 102
ID_SAVEAS = 103
ID_EXIT = 104

ID_CUT = 105
ID_COPY = 106
ID_PASTE = 107
ID_DEL = 108
ID_SELECTALL = 109

class MainWindow(wx.Frame):
	def __init__(self, parent, id, title):
		wx.Frame.__init__(self, parent, wx.ID_ANY, title, size = (600,600), style = wx.DEFAULT_FRAME_STYLE | wx.NO_FULL_REPAINT_ON_RESIZE)
		self.grid = gridlib.Grid(self, wx.ID_ANY) #, style = wx.TE_MULTILINE)
		
		# initialized variables
		self.FileOpen = 0 # Has the a file been open, otherwise use saveas
		self.dirname = ''
		self.filename = ''
		
		# Draw a status bar
		self.statusbar = self.CreateStatusBar()
		self.StatusBar.SetFieldsCount(3)
		# mean, median, mode, range, min/max, number of elements, standard deviation?  etc
		# status bar to be used to display some of these
		self.StatusBar.SetStatusWidths([-5, -1, -2])
		
		# File Menu
		fileMenu = wx.Menu()
		fileMenu.Append(ID_NEW, "&New...\tCtrl+N", "Open a new editor window...")
		fileMenu.Append(ID_OPEN, "&Open...\tCtrl+O", "Open a file...")
		fileMenu.Append(ID_SAVE, "&Save\tCtrl+S", "Save your current file")
		fileMenu.Append(ID_SAVEAS, "S&ave As...", "Save as a new file... ")
		fileMenu.AppendSeparator()
		fileMenu.Append(ID_EXIT, "E&xit\tCtrl+Q", "Exit")
		
		# Edit menu
		editMenu = wx.Menu()
		editMenu.Append(ID_CUT, "Cut\tCtrl+X", "Cut selection")
		editMenu.Append(ID_COPY, "Copy\tCtrl+C", "Copy selection")
		editMenu.Append(ID_PASTE, "Paste\tCtrl+V", "Paste previously cut or copied information")
		editMenu.Append(ID_DEL, "Delete", "Delete selection")
		editMenu.AppendSeparator()
		editMenu.Append(ID_SELECTALL, "Select All\tCtrl+A", "Select All")
		
		# Set Menu Bar with previously defined listings (File, edit, etc)
		menubar = wx.MenuBar()
		menubar.Append(fileMenu, "&File")
		menubar.Append(editMenu, "&Edit")
		self.SetMenuBar(menubar)
		
		# Events
		wx.EVT_MENU(self, ID_NEW, self.OnNewDoc)
		wx.EVT_MENU(self, ID_OPEN, self.OnOpen)
		wx.EVT_MENU(self, ID_SAVE, self.OnSave)
		wx.EVT_MENU(self, ID_SAVEAS, self.OnSaveAs)
		wx.EVT_MENU(self, ID_EXIT, self.OnExit)

		wx.EVT_MENU(self, ID_CUT, self.OnCut)
		wx.EVT_MENU(self, ID_COPY, self.OnCopy)
		wx.EVT_MENU(self, ID_PASTE, self.OnPaste)
		wx.EVT_MENU(self, ID_DEL, self.OnDelete)
		wx.EVT_MENU(self, ID_SELECTALL, self.OnSelectAll)
		
		# self.Bind(gridlib.EVT_GRID_CELL_LEFT_CLICK, self.OnCellLeftClick)
		# self.Bind(gridlib.EVT_GRID_CELL_RIGHT_CLICK, self.OnCellRightClick)
		# self.Bind(gridlib.EVT_GRID_CELL_LEFT_DCLICK, self.OnCellLeftDClick)
		# self.Bind(gridlib.EVT_GRID_CELL_RIGHT_DCLICK, self.OnCellRightDClick)
		
		self.Bind(gridlib.EVT_GRID_RANGE_SELECT, self.OnRangeSelect)
		# self.Bind(gridlib.EVT_GRID_CELL_CHANGE, self.OnCellChange)
		# self.Bind(gridlib.EVT_GRID_SELECT_CELL, self.OnSelectCell)
		
		
		self.grid.CreateGrid(25, 25)
		self.grid.SetColSize(3, 25)
		self.grid.SetRowSize(4, 45)
		
		self.Show(True)
	def OnRangeSelect(self, evt):
		if evt.Selecting():
			print evt.GetTopLeftCoords(), evt.GetBottomRightCoords()
			#write("OnRangeSelect: top-left %s, bottom-right %s\n" % (evt.GetTopLeftCoords(), evt.GetBottomRightCoords()))
		evt.Skip()

	def OnNewDoc(self, event):
		newFile = MainWindow(None, -1, "basicStat")
		#newFile.Centre()
		newFile.Show()
		
	def OnOpen(self, event): # Open a file
		""" Open a file """
		dlg = wx.FileDialog(self, "Choose a file", self.dirname, "", "*.*", wx.OPEN)
		if dlg.ShowModal() == wx.ID_OK:
			self.filename = dlg.GetFilename()
			self.dirname = dlg.GetDirectory()
			f = open(os.path.join(self.dirname,self.filename),'r')
			self.grid.SetValue(f.read())
			self.SetTitle("Noober Editor - " + dlg.GetPath())
			self.FileOpen = 1
			#self.PositionUpdate()
			f.close()
		dlg.Destroy()
		
	def OnSave(self, event): # Save a file 
		""" Save the file to the original file location .... otherwise use saveas """
		if self.FileOpen == 1:
			f = open(os.path.join(self.dirname,self.filename), "w")
			f.write(self.grid.GetValue())
			self.SetStatusText("Contents written to " +self.dirname+"\\"+self.filename)
			f.close()
		else:
			self.OnSaveAs(event)
	
	def OnSaveAs(self, event): # Save file to a new path
		""" Save to an arbitrary file and path """
		dlg = wx.FileDialog(self, "Save As", self.dirname, self.filename, "Text Files (*.txt)|*.txt|All Files|*.*", wx.SAVE)
		if (dlg.ShowModal() == wx.ID_OK):
			self.filename = dlg.GetFilename()
			self.dirname = dlg.GetDirectory()
			self.SetTitle("Noober Editor - " + dlg.GetPath())
			self.FileOpen = 1
			self.OnSave(event)
		dlg.Destroy()

	def OnCut(self, event): # Cut selection
		""" Cuts the selection """
		self.grid.Cut()
		self.PositionUpdate()
	
	def OnCopy(self, event): # Copy Selection
		""" Copies the selection """
		self.grid.Copy()
		self.PositionUpdate()
		
	def OnPaste(self, event): # Paste Selection
		""" Paste the Cut or Copied elements from the clipboard """
		self.grid.Paste()
		self.PositionUpdate()
	
	def OnDelete(self, event): # Delete the selection
		""" Deletes the selected portion """
		fromHere, toHere = self.control.GetSelection()
		self.control.Remove(fromHere, toHere)
	
	def OnSelectAll(self, event): # Select the whole document
		""" Select all the contents of the TextCtrl """
		self.grid.SelectAll()
		self.PositionUpdate()

	def OnExit(self, event): # exit the program
		""" Kill the program """
		self.Close(True)
	# def OnExit(self, event):
		# if self.modify:
			# dlg = wx.MessageDialog(self, 'Save before Exit?', '', wx.YES_NO | wx.YES_DEFAULT | 
			# wx.CANCEL | wx.ICON_QUESTION)
			# val = dlg.ShowModal()
			# if val == wx.ID_YES:
				# self.OnSaveFile(event)
				# if not self.modify:
					# wx.Exit()
			# elif val == wx.ID_CANCEL:
				# dlg.Destroy()
			# else:
				# self.Destroy()
		# else:
			# self.Destroy()
			
if __name__ == "__main__":
	app = wx.App(0)
	frame = MainWindow(None, -1, "basicStat")
	app.MainLoop()